package top.continew.admin.generator.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencentcloudapi.ecm.v20190719.models.Province;
import lombok.RequiredArgsConstructor;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import top.continew.admin.generator.model.entity.ProvinceDivisionsDO;
import top.continew.admin.generator.model.query.ProvinceDivisionsQuery;
import top.continew.admin.generator.model.resp.ProvinceDivisionsResp;
import top.continew.admin.generator.service.ProvinceDivisionsService;
import top.continew.admin.system.model.query.UserQuery;
import top.continew.admin.system.model.resp.user.UserResp;
import top.continew.admin.system.service.UserService;
import top.continew.starter.core.exception.BusinessException;
import top.continew.starter.data.mp.base.BaseMapper;
import top.continew.starter.extension.crud.model.entity.BaseIdDO;
import top.continew.starter.extension.crud.model.resp.IdResp;
import top.continew.starter.extension.crud.service.BaseServiceImpl;
import top.continew.admin.generator.mapper.ProvinceLeadersMapper;
import top.continew.admin.generator.model.entity.ProvinceLeadersDO;
import top.continew.admin.generator.model.query.ProvinceLeadersQuery;
import top.continew.admin.generator.model.req.ProvinceLeadersReq;
import top.continew.admin.generator.model.resp.ProvinceLeadersDetailResp;
import top.continew.admin.generator.model.resp.ProvinceLeadersResp;
import top.continew.admin.generator.service.ProvinceLeadersService;
import top.continew.starter.extension.crud.model.resp.PageResp;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.continew.admin.system.model.req.OptionReq;
import cn.hutool.core.util.StrUtil;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.json.XMLTokener.entity;

/**
 * 省区负责人业务实现
 *
 * @author jiangjun
 * @since 2025/06/24 10:40
 */
@Service
@RequiredArgsConstructor
public class ProvinceLeadersServiceImpl extends BaseServiceImpl<ProvinceLeadersMapper, ProvinceLeadersDO, ProvinceLeadersResp, ProvinceLeadersDetailResp, ProvinceLeadersQuery, ProvinceLeadersReq> implements ProvinceLeadersService {

    private final ProvinceDivisionsService  provinceDivisionsService;

    private final UserService userService;

    @Override
    public ProvinceLeadersDetailResp get(Long id) {
        return baseMapper.selectByIdWithAuth(id);
    }
    
    @Override
    public PageResp<ProvinceLeadersResp> pageWithAuth(ProvinceLeadersQuery query, Page<ProvinceLeadersDO> page) {
        IPage<ProvinceLeadersResp> result = baseMapper.selectPageWithAuth(page, query);
        return PageResp.build(result);
    }

    @Transactional
    @Override
    public IdResp<Long> save(ProvinceLeadersReq req) {
        String provinceCode = req.getProvinceCode();
        Long userId = req.getUserId();
        LambdaQueryWrapper<ProvinceLeadersDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProvinceLeadersDO::getProvinceCode, provinceCode)
                .eq(ProvinceLeadersDO::getUserId, userId);
        List<ProvinceLeadersDO> list = baseMapper.selectList(wrapper);
        if (list.size() > 0) {
            throw new BusinessException("该省区已有负责人");
        }
        ProvinceDivisionsQuery query =  new ProvinceDivisionsQuery();
        query.setCode(provinceCode);
        List<ProvinceDivisionsResp> divisionsRespList = provinceDivisionsService.list(query, null);
        if (divisionsRespList.size() == 0) {
            throw new BusinessException("该省区不存在");
        }
        req.setProvinceName(divisionsRespList.get(0).getName());

        UserQuery userQuery =  new UserQuery();
        userQuery.setUserIds(Arrays.asList(userId));
        List<UserResp> userRespList = userService.list(userQuery, null);
        if (userRespList.size() == 0) {
            throw new BusinessException("该用户不存在");
        }
        req.setUserName(userRespList.get(0).getNickname());
        req.setUserPhone(userRespList.get(0).getPhone());
        return new IdResp(create(req));
    }

    @Transactional
    @Override
    public void updateCustom(ProvinceLeadersReq req, Long id) {
        /*ProvinceLeadersDO provinceLeadersDO = this.getById(id);
        if (provinceLeadersDO == null) {
            throw new BusinessException("该省区负责人不存在");
        }
        BeanUtil.copyProperties(req, provinceLeadersDO, CopyOptions.create().ignoreNullValue());

        ProvinceDivisionsQuery query =  new ProvinceDivisionsQuery();
        query.setCode(req.getProvinceCode());
        List<ProvinceDivisionsResp> divisionsRespList = provinceDivisionsService.list(query, null);
        if (divisionsRespList.size() == 0) {
            throw new BusinessException("该省区不存在");
        }
        provinceLeadersDO.setProvinceName(divisionsRespList.get(0).getName());
        UserQuery userQuery =  new UserQuery();
        userQuery.setUserIds(Arrays.asList(req.getUserId()));
        List<UserResp> userRespList = userService.list(userQuery, null);
        if (userRespList.size() == 0) {
            throw new BusinessException("该用户不存在");
        }
        provinceLeadersDO.setUserName(userRespList.get(0).getUsername());
        provinceLeadersDO.setUserPhone(userRespList.get(0).getPhone());
        updateById(provinceLeadersDO);*/
    }

    @Override
    public List<OptionReq> getAllLeaders(String keyword) {
        LambdaQueryWrapper<ProvinceLeadersDO> wrapper = new LambdaQueryWrapper<>();
        
        if (StrUtil.isNotBlank(keyword)) {
            wrapper.and(w -> w.like(ProvinceLeadersDO::getUserName, keyword)
                    .or().like(ProvinceLeadersDO::getUserPhone, keyword)
                    .or().like(ProvinceLeadersDO::getProvinceName, keyword));
        }
        
        List<ProvinceLeadersDO> leaders = this.list(wrapper);
        
        return leaders.stream()
                .map(leader -> {
                    OptionReq option = new OptionReq();
                    option.setCode(leader.getUserName() + (StrUtil.isNotBlank(leader.getUserPhone()) ? " (" + leader.getUserPhone() + ")" : ""));
                    option.setValue(leader.getUserId().toString());
                    return option;
                })
                .collect(Collectors.toList());
    }
}